package org.nnxy.foodboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.nnxy.foodboot.common.Result;
import org.nnxy.foodboot.entity.UserBrowseHistory;
import org.nnxy.foodboot.entity.UserCollection;
import org.nnxy.foodboot.entity.UserRating;
import org.nnxy.foodboot.entity.UserRecipeInteraction;
import org.nnxy.foodboot.service.UserBrowseHistoryService;
import org.nnxy.foodboot.service.UserCollectionService;
import org.nnxy.foodboot.service.UserRatingService;
import org.nnxy.foodboot.service.UserRecipeInteractionService;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户食谱交互控制器
 */
@RestController
@RequestMapping("/api/user/interaction")
@RequiredArgsConstructor
public class UserRecipeInteractionController {
    
    private final UserRecipeInteractionService userRecipeInteractionService;
    private final UserBrowseHistoryService userBrowseHistoryService;
    private final UserCollectionService userCollectionService;
    private final UserRatingService userRatingService;
    
    /**
     * 获取用户与食谱的交互记录
     */
    @GetMapping("/{userId}/{recipeId}")
    public Map<String, Object> getUserRecipeInteraction(
            @PathVariable Integer userId,
            @PathVariable Integer recipeId) {
        
        UserRecipeInteraction interaction = userRecipeInteractionService.getInteractionByUserIdAndRecipeId(userId, recipeId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("data", interaction);
        return result;
    }
    
    /**
     * 分页获取用户的交互记录
     */
    @GetMapping("/page")
    public Map<String, Object> getUserInteractionsPage(
            @RequestParam Integer userId,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        
        Page<UserRecipeInteraction> page = userRecipeInteractionService.getUserInteractionsPage(
                new Page<>(current, size), userId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("data", page);
        return result;
    }
    
    /**
     * 更新用户浏览食谱记录
     */
    @PostMapping("/browse")
    public Map<String, Object> updateBrowseRecord(
            @RequestParam Integer userId,
            @RequestParam Integer recipeId) {
        
        boolean success = userRecipeInteractionService.updateBrowseRecord(userId, recipeId);
        
        Map<String, Object> result = new HashMap<>();
        if (success) {
            result.put("code", 200);
            result.put("message", "记录成功");
        } else {
            result.put("code", 500);
            result.put("message", "记录失败");
        }
        return result;
    }
    
    /**
     * 更新用户收藏食谱记录
     */
    @PostMapping("/favorite")
    public Map<String, Object> updateFavoriteRecord(
            @RequestParam Integer userId,
            @RequestParam Integer recipeId,
            @RequestParam Boolean isFavorite) {
        
        boolean success = userRecipeInteractionService.updateFavoriteRecord(userId, recipeId, isFavorite);
        
        Map<String, Object> result = new HashMap<>();
        if (success) {
            result.put("code", 200);
            result.put("message", isFavorite ? "收藏成功" : "取消收藏成功");
        } else {
            result.put("code", 500);
            result.put("message", isFavorite ? "收藏失败" : "取消收藏失败");
        }
        return result;
    }
    
    /**
     * 更新用户对食谱的评分和评价
     */
    @PostMapping("/rating")
    public Map<String, Object> updateRatingRecord(
            @RequestParam Integer userId,
            @RequestParam Integer recipeId,
            @RequestParam BigDecimal rating,
            @RequestParam(required = false) String review) {
        
        boolean success = userRecipeInteractionService.updateRatingRecord(userId, recipeId, rating, review);
        
        Map<String, Object> result = new HashMap<>();
        if (success) {
            result.put("code", 200);
            result.put("message", "评分成功");
        } else {
            result.put("code", 500);
            result.put("message", "评分失败");
        }
        return result;
    }
    
    /**
     * 更新用户制作食谱记录
     */
    @PostMapping("/make")
    public Map<String, Object> updateMakeRecord(
            @RequestParam Integer userId,
            @RequestParam Integer recipeId,
            @RequestParam(required = false) String satisfactionLevel) {
        
        boolean success = userRecipeInteractionService.updateMakeRecord(userId, recipeId, satisfactionLevel);
        
        Map<String, Object> result = new HashMap<>();
        if (success) {
            result.put("code", 200);
            result.put("message", "记录成功");
        } else {
            result.put("code", 500);
            result.put("message", "记录失败");
        }
        return result;
    }
    
    /**
     * 获取用户交互统计信息
     */
    @GetMapping("/stats/{userId}")
    public Result<Map<String, Object>> getUserInteractionStats(@PathVariable Integer userId) {
        Map<String, Object> stats = userRecipeInteractionService.getUserInteractionStats(userId);
        return Result.success(stats);
    }
    
    /**
     * 获取用户详细交互统计信息
     */
    @GetMapping("/stats/detail/{userId}")
    public Result<Map<String, Object>> getUserDetailedStats(@PathVariable Integer userId) {
        Map<String, Object> detailedStats = new HashMap<>();
        
        // 获取基本统计信息
        Map<String, Object> basicStats = userRecipeInteractionService.getUserInteractionStats(userId);
        detailedStats.putAll(basicStats);
        
        // 获取其他统计信息
        try {
            // 获取最受欢迎的食谱分类
            List<Map<String, Object>> favoriteCategories = userRecipeInteractionService.getUserFavoriteCategories(userId, 5);
            detailedStats.put("favoriteCategories", favoriteCategories);
            
            // 获取用户评分分布
            Map<String, Long> ratingDistribution = userRecipeInteractionService.getUserRatingDistribution(userId);
            detailedStats.put("ratingDistribution", ratingDistribution);
            
            // 获取用户活跃度统计(最近一周)
            Map<String, Long> activityStats = userRecipeInteractionService.getUserActivityByDay(userId, 7);
            detailedStats.put("activityByDay", activityStats);
            
            // 获取用户最近交互的食谱
            List<Map<String, Object>> recentInteractions = userRecipeInteractionService.getRecentInteractions(userId, 5);
            detailedStats.put("recentInteractions", recentInteractions);
            
            return Result.success(detailedStats);
        } catch (Exception e) {
            return Result.error("获取详细统计信息失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户统一统计接口（包含历史浏览、收藏、评分数量）
     */
    @GetMapping("/user-stats")
    public Result<Map<String, Object>> getUserStats(@RequestParam Long userId) {
        Map<String, Object> stats = new HashMap<>();
        
        try {
            // 统计浏览历史数量
            long browseCount = userBrowseHistoryService.count(
                new LambdaQueryWrapper<UserBrowseHistory>()
                    .eq(UserBrowseHistory::getUserId, userId)
                    .eq(UserBrowseHistory::getDelFlag, "0")
            );
            
            // 统计收藏数量
            long collectionCount = userCollectionService.count(
                new LambdaQueryWrapper<UserCollection>()
                    .eq(UserCollection::getUserId, userId)
            );
            
            // 统计评分数量
            long ratingCount = userRatingService.count(
                new LambdaQueryWrapper<UserRating>()
                    .eq(UserRating::getUserId, userId)
                    .eq(UserRating::getDelFlag, "0")
            );
            
            stats.put("browseCount", browseCount);
            stats.put("collectionCount", collectionCount);
            stats.put("ratingCount", ratingCount);
            
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error("获取用户统计信息失败: " + e.getMessage());
        }
    }
} 